<?php
namespace Admin\Controller;
use Think\Controller;
use Common\BaseController;
use Think\Upload;
use Common\Common\Log;
class AdminController extends BaseController {


    //用户信息
    public function info(){
        $User = M('User'); // 实例化User对象
        $count      = $User->where('status=1')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $User->where('status=1')->order('create_time')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }


   //添加用户
    public function add()
    {
        $tmplData['title'] = '新增人员'; // 标题

        if(I( 'post.' )){
            if(session('checkDataKey')==$this->createCheckDataKey(I( 'post.' ))){
                // 验证已通过
                // 上传文件处理
                $config = array(
                    'savePath' => '/Admin/',
                    'saveName' => array('uniqid',''),
                    'exts' => array('jpg','gif','png','jpeg'),
                    'autoSub' => true,
                    'subName' => 'user',
                );
                $upload = new Upload( $config );
                $info = $upload->upload();//上传文件信息
                $this->thumb($info);//裁剪上传文件

                $data['username'] = I( 'post.username' );
                $data['password'] = $this->encryption('bank', I( 'post.password' ) );
                $data['sex'] = I( 'post.sex' );
                $data['id_code'] = I( 'post.id_code' );
                $data['role_id'] = I( 'post.role_id' );
                $data['tel'] = I( 'post.tel' );
                $data['email'] = I( 'post.email' );
                $data['create_time'] = date( 'Y-m-d H:i:s' );
                $data['id_photo'] = $info['biz_certificate']['savepath'].$info['biz_certificate']['savename'];

                if(M( 'User' )->data( $data )->add()){
                    $lastInsId=M('BankUser')->getLastInsID();
                    $url='info';
                    $param='userId='.$lastInsId;
                    $content='新增人员成功';
                    Log::write2($content);
                    $this->showMsg('添加成功！','success',$url,$param);
                }else{
                    $this->showMsg('添加失败！','error',$url,$param);
                }
            }else{
                $this->showMsg('操作异常！','warning');
            }
        }
        $this->assign( $tmplData );
        $this->display();
    }
    //验证用户唯一性
    public function checkUserUnique(){
           if(I("post.type")){
               //验证后台用户
               if(I('post.username')){
                   if(I("post.id")){
                       $id=I("post.id");
                       $where="username='%s' AND id !=".$id."";
                   }else{
                       $where="username='%s'";
                   }
                   if(M('Admin')->where($where,I('post.username'))->count()){
                       $data=array(
                           'tips'=>'用户名已经被使用！',
                       );
                   }else{
                       $data=array(
                           'tips'=>'',
                       );
                   }
               }else{
                   $data=array(
                       'tips'=>'系统异常！',
                   );
               }
           }else{
               //验证前台用户
               if(I('post.username')){
                   if(I("post.id")){
                       $id=I("post.id");
                       $where="username='%s' AND id !=".$id."";
                   }else{
                       $where="username='%s'";
                   }
                   if(M('User')->where($where,I('post.username'))->count()){
                       $data=array(
                           'tips'=>'用户名已经被使用！',
                       );
                   }else{
                       $data=array(
                           'tips'=>'',
                       );
                   }

               }else{
                   $data=array(
                       'tips'=>'系统异常！',
                   );
               }
           }

        $this->ajaxReturn($data);
    }

    /**
     * 检查联系方式是否被用
     */
    public function checkTelUnique(){
        if(I("post.type")){
            if(I('post.tel')){
                if(!I('post.id')){
                    $where='tel="%s"';
                }else{
                    $id=I('post.id');
                    $where="id !='{$id}' AND tel='%s'";
                }
                if(M('Admin')->where($where,I('post.tel'))->count()){
                    $data=array(
                        'tips'=>'联系方式已经被使用！',
                    );
                }else{
                    $data=array(
                        'tips'=>'',
                    );
                }
            }else{
                $data=array(
                    'tips'=>'系统异常！',
                );
            }
        }else{
            if(I('post.tel')){
                if(!I('post.id')){
                    $where='tel="%s"';
                }else{
                    $id=I('post.id');
                    $where="id !='{$id}' AND tel='%s'";
                }
                if(M('User')->where($where,I('post.tel'))->count()){
                    $data=array(
                        'tips'=>'联系方式已经被使用！',
                    );
                }else{
                    $data=array(
                        'tips'=>'',
                    );
                }
            }else{
                $data=array(
                    'tips'=>'系统异常！',
                );
            }
        }
        $this->ajaxReturn($data);
    }

  //验证邮箱的唯一性
    public function checkEmailUnique()
    {
            if(I("post.type")){
                if(I('post.email')){
                    if(!I('post.id')){
                        $where='email="%s"';
                    }else{
                        $id=I('post.id');
                        $where="id !='{$id}' AND email='%s'";
                    }
                    if(M('Admin')->where($where,I('post.email'))->count()){
                        $data=array(
                            'tips'=>'邮箱已经被使用！',
                        );
                    }else{
                        $data=array(
                            'tips'=>'',
                        );
                    }
                }else{
                    $data=array(
                        'tips'=>'系统异常！',
                    );
                }
            }else{
                if(I('post.email')){
                    if(!I('post.id')){
                        $where='email="%s"';
                    }else{
                        $id=I('post.id');
                        $where="id !='{$id}' AND email='%s'";
                    }
                    if(M('User')->where($where,I('post.email'))->count()){
                        $data=array(
                            'tips'=>'邮箱已经被使用！',
                        );
                    }else{
                        $data=array(
                            'tips'=>'',
                        );
                    }
                }else{
                    $data=array(
                        'tips'=>'系统异常！',
                    );
                }
            }

        $this->ajaxReturn($data);
    }

    /**
     * 后台用户修改
     */
    public function editAdmin(){
        $tmplData['title'] = '用户修改'; // 标题

        if(I( 'post.' )){
            if(session('checkDataKey')==$this->createCheckDataKey(I( 'post.' ))){
                // 验证已通过
                $data['username'] = I( 'post.username' );
                $data['tel'] = I( 'post.tel' );
                $data['eName'] = I( 'post.eName' );
                $userId=I('post.userId');
                //没有上传文件
                $url='admin/bglist';

                $role_id=I("post.role_id");
                $roleData=array();
                foreach($role_id as $k=>$v){
                    $roleData[]=array(
                        'admin_id'=>$userId,
                        'role_id'=>$v
                    );
                }
                if(M( 'Admin' )->data($data)->where('id="%d"',$userId)->save()){
                    $flag=false;
                    if(M("Admin_role")->where('admin_id="%d"',$userId)->delete()){
                       $flag=true;
                    }
                    if($flag){
                        $res=M("Admin_role")->addAll($roleData);
                    }
                    $content='人员信息修改成功';
                    Log::write2($content);
                    if($res){
                        $this->showMsg('修改成功！','success',$url);
                    }else{
                        $this->showMsg('角色分配失败！','error',$url);
                    }
                }else{
                    $flag=false;
                    if(M('AdminRole')->where("admin_id='%d'",$userId)->count()){
                        if(M("AdminRole")->where('admin_id='.$userId.'')->delete()){
                            $flag=true;
                        }
                    }else{
                        $flag=true;
                    }
                    if($flag){
                        if(M("Admin_role")->addAll($roleData)){
                            $content='人员信息修改成功';
                            Log::write2($content);
                            $this->showMsg('修改成功！','success',$url);
                        }else{
                            $this->showMsg('修改失败！','error',$url);
                        }
                    }
                        $this->showMsg('修改失败！','error',$url);
                }
            }else{
                $this->showMsg('操作异常！','warning','admin/info');
            }
        }else{
            //查询记录
            $userId=I('get.userId');
            $re=M('Admin')->where('id="%d"',$userId)->find();
            if($re){
                $tmplData['userId']=$re['id'];
                $tmplData['username']=$re['username'];
                $tmplData['password']=123456;
                $tmplData['eName']=$re['eName'];
                $tmplData['tel']=$re['tel'];
            }else{
                $url='bglist';
                $this->showMsg('操作异常！','warning',$url);
            }
            $role=M("Role")->where("status=1")->select();  //所有的角色
            $role_id=M('Admin_role')->where("admin_id='%d'",$userId)->select(); //查询拥有的角色id
            $arr=array();
            foreach($role_id as $k=>$v){
                $arr[]=$v['role_id'];
            }
            $tmplData['role']=$role;
            $tmplData['have_role']=$arr;
            $this->assign( $tmplData );
            $this->display();
        }

    }

    /**
     * 人员修改
     */
    public function editUser(){
        $tmplData['title'] = '人员修改'; // 标题

        if(I( 'post.' )){
            if(session('checkDataKey')==$this->createCheckDataKey(I( 'post.' ))){
                // 验证已通过
                $data['username'] = I( 'post.username' );
                $data['tel'] = I( 'post.tel' );
                $data['email'] = I( 'post.email' );
                $userId=I('post.userId');
                    //没有上传文件
                     $url='admin/info';
                    if(M( 'User' )->data($data)->where('id="%d"',$userId)->save()){

                        $content='人员信息修改成功';
                        Log::write2($content);
                        $this->showMsg('修改成功！','success',$url);
                    }else{
                        $this->showMsg('修改失败！','error',$url);
                    }
            }else{
                $this->showMsg('操作异常！','warning','admin/info');
            }
        }else{
            //查询记录
            $userId=I('get.userId');
            $re=M('User')->where('id="%d"',$userId)->find();
            if($re){
                $tmplData['userId']=$re['id'];
                $tmplData['username']=$re['username'];
                $tmplData['sex']=$re['sex'];
                $tmplData['id_code']=$re['id_code'];
                $tmplData['id_photo']=$re['id_photo'];
                $tmplData['photo_name']=substr($re['id_photo'],strripos($re['id_photo'],"/")+1);
                $tmplData['tel']=$re['tel'];
                $tmplData['email']=$re['email'];
            }else{
                $url='info';
                $this->showMsg('操作异常！','warning',$url);
            }
            $this->assign( $tmplData );
            $this->display('edit');
        }

    }
    //删除前台用户
    public function delUser()
    {
        $userId=I('get.userId');
        $url='admin/info';
        if(M("User")->where('id="%d"',$userId)->setField('status',0))
        {
            $content='人员删除成功';
            Log::write2($content);
            $this->showMsg('删除成功！','success',$url);
        }else{
            $this->showMsg('删除失败！','error',$url);
        }
    }
    //删除后台用户
    public function delAdmin()
    {
        $userId=I('get.userId');
        $url='admin/bglist';
        if(M("Admin")->where('id="%d"',$userId)->setField('status',0))
        {
            $content='用户删除成功';
            Log::write2($content);
            $this->showMsg('删除成功！','success',$url);
        }else{
            $this->showMsg('删除失败！','error',$url);
        }
    }
    //后台人员列表
    public function bglist()
    {
        $temdata['title']="用户列表";
        $User = M('Admin'); // 实例化Admin对象
        $count      = $User->where('status=1')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $User->where('status=1')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($list as $k=>$v)
        {
            if($v['level']==1){
                unset($list[$k]);
            }
        }
        foreach($list as $k=>$v){
            $role_id=M("Admin_role")->where("admin_id='%d'",$v['id'])->select();
            if(!empty($role_id)){
                 $role_name="";
                foreach($role_id as $key=>$val){
                    $role=M("Role")->where("id='%d' AND status=1",$val['role_id'])->find();
                    if(!empty($role)){
                        $role_name.=",".$role['role_name'];
                    }
                }
                $list[$k]['role_name']=substr($role_name,1);
            }
        }
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->assign($temdata);
        $this->display();
    }
    //后台用户添加
    public function addbg()
    {
        $tmplData['title'] = '新增用户'; // 标题

        if(I( 'post.' )){
            if(session('checkDataKey')==$this->createCheckDataKey(I( 'post.' ))){
                // 验证已通过
                $data['username'] = I( 'post.username' );
                $data['password'] = $this->encryption('bank', I( 'post.password' ) );
                $data['eName'] = I( 'post.eName' );
                $data['tel'] = I( 'post.tel' );
                $url='admin/bglist';
                if(M( 'Admin' )->data( $data )->add()){
                    $lastInsId=M('Admin')->getLastInsID();

                    $param='userId='.$lastInsId;
                    $content='新增用户成功';
                    Log::write2($content);
                    $role=I("post.role_id");
                    foreach($role as $k=>$v){
                        $res=M("Admin_role")->data(array("role_id"=>$v,"admin_id"=>$lastInsId))->add();
                    }
                    if($res){
                        $this->showMsg('添加成功！','success',$url,$param);
                    }else{
                        $this->showMsg('角色分配失败！','error',$url);
                    }
                }else{
                    $this->showMsg('添加失败！','error',$url);
                }
            }else{
                $this->showMsg('操作异常！','warning');
            }
        }
        $res=M("role")->select();
        $this->assign("role",$res);
        $this->assign( $tmplData );
        $this->display();
    }

    /**
     * 数据验证
     */
    public function ajaxCheckData(){
        // 验证场景
        $scene = I( 'get.scene' );
        // 验证数据
        $data = I( 'post.' );
        switch($scene){
            case 'addUser' :
                $User = D( 'User' );
                // error:0:没有错误,1:有错误 errInfo:有错时为错误信息(数组格式),否则为空, verify:验证通过置为ok,否则置为空
                if(!$User->create( $data ,'add' )){
                    // 验证不通过
                    $reData = array(
                        'error' => 1,
                        'errInfo' => $User->getError(),
                    );
                } else{
                    // 验证通过
                    session('checkDataKey',$this->createCheckDataKey($data));
                    $reData = array(
                        'error' => 0,
                        'errInfo' => '',
                    );
                }
                break;
            case 'editUser' :
                $User = D( 'User' );
                $User->id=$data['id'];
                // error:0:没有错误,1:有错误 errInfo:有错时为错误信息(数组格式),否则为空, verify:验证通过置为ok,否则置为空
                if(!$User->create( $data,'edit')){
                    // 验证不通过
                    $reData = array(
                        'error' => 1,
                        'errInfo' => $User->getError(),
                    );
                }else{
                    // 验证通过
                    unset($data['id']);
                    session('checkDataKey',$this->createCheckDataKey($data));
                    $reData = array(
                        'error' => 0,
                        'errInfo' => '',
                    );
                }
                break;
            case 'addAdmin' :
                $BankBgUser = D( 'Admin' );
                // error:0:没有错误,1:有错误 errInfo:有错时为错误信息(数组格式),否则为空, verify:验证通过置为ok,否则置为空
                if(!$BankBgUser->create( $data ,'add' )){
                    // 验证不通过
                    $reData = array(
                        'error' => 1,
                        'errInfo' => $BankBgUser->getError(),
                    );
                }else{
                    // 验证通过
                    session('checkDataKey',$this->createCheckDataKey($data));
                    $reData = array(
                        'error' => 0,
                        'errInfo' => '',
                    );
                }
                break;
            case 'editAdmin' :
                $Admin = D( 'Admin' );
                $Admin->id=$data['id'];
                // error:0:没有错误,1:有错误 errInfo:有错时为错误信息(数组格式),否则为空, verify:验证通过置为ok,否则置为空
                if(!$Admin->create( $data,'edit')){
                    // 验证不通过
                    $reData = array(
                        'error' => 1,
                        'errInfo' => $Admin->getError(),
                    );
                } else{
                    // 验证通过
                    unset($data['id']);
                    session('checkDataKey',$this->createCheckDataKey($data));
                    $reData = array(
                        'error' => 0,
                        'errInfo' => '',
                    );
                }
                break;
            default	:
                $reData = array(
                    'error' => 1,
                    'errInfo' => '',
                );
                break;
        }
        $this->ajaxReturn( $reData );
    }


}